<?php

namespace app\common\service;

use app\common\service\Base;
use app\common\service\Sku as SkuService;
use think\facade\Cache;

/**
 * 自定义导出
 * @author zhuguosen 905502314@qq.com
 * @date 2022/6/7
 * @package app\common\service
 */
class UserDefinedGet extends Base
{
    public $order_kv;
    public $material_kv;
    public $label_real;
    public $head_flag;

    public function __construct()
    {
        $this->order_kv = [
            'create_time' => '下单时间',
            'pic' => '图片',
            'client_ordernum' => '客户订单号',
            'type' => '订单类型',
            'create_time_diff' => '订单时效',
            'status' => '作废状态',
            'sku' => 'SKU',
            'daohuo_count' => '出货数',
            'jiaohuo_count' => '车间数',
            'shicai_count' => '裁床数',
            'quantity' => '订单数量',
            'factory_name' => '工厂',
            'group_name' => '分组',
            'caigou_over_time' => '采购时间',
            'caichuang_over_time' => '裁床时间',
            'chejian_over_time' => '车间时间',
            'tail_over_time' => '尾部时间',
            'group_name' => '产品分组',
            'remark' => '备注',
            'factory_outgo_name' => '外发工厂',
            'price' => '售价',
            'cost' => 'MES加工费含倍率',
            'material_cost_little' => 'MES物料费',
            'material_cost_total' => 'MES物料费(含利润)',
            'cost_profit' => 'MES加工费(含利润)',
            'shipment_time' => '货期',
            'is_auto_import' => '来源账号',
            'is_public' => '是否公共款',
            'style_name' => '款式',
            'sku_type' => '品类',
            'supplier' => '面料供应商',
            'off_pressing_level' => '大烫',
            'special_process_a_name' => '二次工艺A',
            'special_process_a_level' => '二次工艺A程度',
            'special_process_a_count' => '二次工艺A数量',
            'special_process_a_unitprice' => '二次工艺A单价',
            'special_process_a_price' => '二次工艺A总价',
            'special_process_b_name' => '二次工艺B',
            'special_process_b_level' => '二次工艺B程度',
            'special_process_b_count' => '二次工艺B数量',
            'special_process_b_unitprice' => '二次工艺B单价',
            'special_process_b_price' => '二次工艺B总价',
            'zj_name' => '二次工艺C',
            'zj_level' => '二次工艺C程度',
            'zj_count' => '二次工艺C数量',
            'zj_unitprice' => '二次工艺C单价',
            'zj_price' => '二次工艺C总价',
            'is_new' => '是否新款',
            'caichuang_position' => '裁剪方式',
        ];
        $this->material_kv = [
            'type' => '面料种类',
            'caigou_user_name' => '采购执行人',
            'name' => '材料名称',
            'material_sku' => '材料SKU',
            'supplier' => '供应商',
            'model' => '型号',
            'material_dosage' => '单件用量',
            'caigou_over_time' => '批色时间',
            'jing_material_dosage' => '采购量',
            'purchasing_unit' => '采购单位',
            'caigou_unitprice' => '单价',
            'shiji_caigou_count' => '实际采购量',
            'tiaoshu' => '条数',

            'st_operate_num' => '材料使用明细',
            'st_remark' => '材料使用操作',
            'caigou_start_time' => '采购时间',
            'tiaoshu_status_time_10' => '换料中时间',
            'caigou_finish_time' => '采购完成时间',
            'arrive_time' => '到料时间',
            'caigou_confirm_time' => '打标时间',
            'caigou_over_time' => '批色通过时间',
            'caigou_over_time_2' => '批色不通过时间',
            'send_goods_time' => '已发货时间（物料进度）',
            'stock_in_time' => '物料入库时间',
            'stock_out_time' => '物料出库时间',
        ];
    }

    /**
     * 查询一定条件下的订单信息
     * @param string $type count获取总数，list具体数据
     * @param int $page
     * @param int $limit
     * @param array $where
     * @param string $label
     * @author zhuguosen 905502314@qq.com
     * @date 2022/6/5
     */
    public function allList($type = 'count', $page = 1, $limit = 20, $whereData = [], $export = true)
    {
        list($where, $whereRaw, $whereHaving, $sql_leftjoin_order_material, $where_material_property) = $this->_where_index($whereData);
        //订单加一级
        order_level($where, 'o.');
        $order = "o.caigou_status asc,o.id desc";

        $count = db('order o')
            ->join('factory ft', "o.factory_id=ft.id", 'left')
            ->join('factory_outgo ftout', "o.factory_outgo_id=ftout.id", 'left')
            ->join('group g', "o.group_id=g.id", 'left')
            ->join('sku s', "o.sku=s.sku", 'left')
            ->join('order_size os ', 'o.id=os.order_id', 'left')
            ->join('system_user su', "o.caigou_user_id=su.id", 'left')
            ->join('order_material om', "o.id=om.order_id {$sql_leftjoin_order_material}", 'left')
            ->join('material m', "om.material_id=m.id", 'left')
            ->join('material_return mr', "om.mid=mr.order_material_id", 'left')
            ->where($where)
            ->whereRaw($whereRaw)
            ->group('o.id')
            ->having($whereHaving)
            ->count();
        if ($type == 'count') {
            return $count;
        }
        $list = db('order o')
            ->field("o.id,o.ext_id,o.client_ordernum,o.`status`,o.sku,o.is_auto_import,o.o_type,o.type
                ,o.factory_id,o.quantity
                ,o.shipment_time,o.over_time,o.create_time,o.caigou_over_time,o.caichuang_over_time
                ,o.chejian_over_time,o.tail_over_time
                ,o.caigou_status,o.caigou_user_id,su.nick as caigou_user_name,o.caigou_remark,o.remark_approval_color
                ,o.outgo_status,ftout.name as factory_outgo_name
                ,o.is_new,o.remark
                ,oext.cost,oext.price,oext.material_cost_little,oext.material_cost_total,oext.cost_profit
,s.pic,s.ori_pic 
,s.is_public,s.style_name,s.sku_type,s.off_pressing_level,s.special_process_a_name,s.special_process_a_level,s.special_process_a_count,s.special_process_a_unitprice,s.special_process_a_price
,s.special_process_b_name,s.special_process_b_level,s.special_process_b_count,s.special_process_b_unitprice,s.special_process_b_price
,s.zj_name,s.zj_level,s.zj_count,s.zj_unitprice,s.zj_price,s.caichuang_position
,ft.name as factory_name,g.name as group_name
,m.name as material_name,m.material_sku,m.supplier
,group_concat(distinct os.mid,',', os.size_name,',',os.order_count ,',',os.shicai_count,',',os.jiaohuo_count,',',os.jiaohuo_tail_count,',',os.delivery_count,',',os.daohuo_count  SEPARATOR ';') as order_size_list
,min(om.caigou_show) as  caigou_show_min ,max(om.caigou_show) as caigou_show_max
,min(om.caigou_status) as caigou_status_min,max(om.caigou_status) as caigou_status_max
,min(om.tiaoshu) as tiaoshu_min ,max(om.tiaoshu) as tiaoshu_max
,min(om.is_caigou_start) as is_caigou_start_min
")
            ->join('order_ext oext', "o.id=oext.order_id", 'left')
            ->join('order_material om', "o.id=om.order_id {$sql_leftjoin_order_material}", 'left')
            ->join('factory ft', "o.factory_id=ft.id", 'left')
            ->join('factory_outgo ftout', "o.factory_outgo_id=ftout.id", 'left')
            ->join('group g', "o.group_id=g.id", 'left')
            ->join('sku s', "o.sku=s.sku", 'left')
            ->join('order_size os ', 'o.id=os.order_id', 'left')
            ->join('system_user su', "o.caigou_user_id=su.id", 'left')
            ->join('material m', "om.material_id=m.id", 'left')
            ->join('material_return mr', "om.mid=mr.order_material_id", 'left')
            ->where($where)
            ->whereRaw($whereRaw)
            ->page($page)->limit($limit)->orderRaw($order)
            ->group('o.id')
            ->having($whereHaving)
//                ->fetchSql(true)
            ->select();
//        $skuService = new SkuService();
        $order_id_array = [];
        $this->_allList_order($list, $order_id_array, $export);
        $list_order_material = db('order_material om')
            ->field("om.mid,om.material_id,om.order_id,om.client_ordernum,om.fabric_width,om.weight
                ,om.material_dosage,om.loss,om.caigou_status,om.factory_id
                ,om.is_make_tag,om.is_caigou_start,om.need_checkcloth,om.need_shrink
                ,om.caigou_unitprice,om.shiji_caigou_count,om.tiaoshu,om.tiaoshu_detail,om.tiaoshu_status,om.return_length
                ,om.arrive_time,om.arrive_time_first,om.caigou_over_time
                ,om.send_goods_status
                ,om.caigou_start_time,om.tiaoshu_status_time,om.caigou_finish_time,om.arrive_time
                ,om.caigou_confirm_time,om.caigou_over_time,om.send_goods_time,om.caigou_status,om.send_goods_status
                ,m.name,m.type,m.type as type_num,m.material_sku,m.model,m.colornum,m.color,m.supplier,m.address,m.contact
                ,m.purchasing_unit
                ,sum(IF(sl.type=0, IFNULL(sl.operate_num, 0),0)) as operate_num_0
                ,sum(IF(sl.type=2, IFNULL(sl.operate_num, 0),0)) as operate_num_2
                ,sum( IFNULL(ms.metre_left, 0) ) as have_metres
                ,sum(IF(msu.status=1, IFNULL(msu.metre, 0),0)) as apply_and_used_0_apply
                ,sum(IF(msu.status=2, IFNULL(msu.metre, 0),0)) apply_and_used_0_used
                ,mi.need_checkcloth as mi_need_checkcloth
                ,count(DISTINCT IF(mi.flag_del=0 and mi.is_checkcloth=1 and mi.is_return=0, mi.id,null)) as cloth_0
                ,count(DISTINCT IF(mi.flag_del=0 and mi.is_shrink=1 and mi.is_return=0, mi.id,null)) as cloth_1
                
                ,count(IF(mr.status <=1 , 1,null)) as material_return_0
                ,count(IF(mr.is_renew=1 and mr.status <>1 , 1,null)) as material_return_1
                ,count(IF(mr.is_renew=1 , 1,null)) as material_return_2
                ")
            ->join('material m', "om.material_id=m.id", 'left')
            ->join('stock_log sl', "m.type='accessories' and om.material_id=sl.material_id and om.order_id=sl.order_id", 'left')
            ->join('material_stock ms', "om.material_id=ms.material_id and ms.cutting_time=0", 'left')
            ->join('material_stock_use msu', "om.order_id=msu.order_id and om.material_id=msu.material_id", 'left')
            ->join('order_material_item mi', "om.order_id=mi.order_id and om.material_id=mi.material_id", 'left')
            ->join('material_return mr', "om.mid=mr.order_material_id", 'left')
            ->join('order o', "o.id=om.order_id", 'left')
            ->where([
                ['om.order_id', 'in', $order_id_array],
                ['om.material_id', '>', 0],
                ['om.caigou_show', '<>', 0],// 去除不在采购进度显示条目
            ])
            ->where($where_material_property)
            ->order('om.caichuang_standard desc')
            ->group('om.mid')
            ->select();
        $this->_allList_order_material($list, $list_order_material, $order_id_array, $export);
        return [
            'code' => 0,
            'msg' => '',
            'data' => $list,
            'count' => $count,
        ];
    }

    private function _allList_order(&$list, &$order_id_array, $export)
    {
        switch ($export) {
            case true:
                $orderTypeMap = config('mimo.order_type');
                $orderFromMap = config('mimo.order_from');
                $processLevelMap = config('mimo.process_level');
                $caichuangPositionMap = config('mimo.caichuang_position');
                foreach ($list as $k => $v) {
                    $list[$k]['create_time'] = intval($v['create_time']) > 0 ? date('Y-m-d H:i:s', intval($v['create_time'])) : '';
                    $list[$k]['type'] = arrayGet($orderTypeMap, $v['type'], '');
                    $list[$k]['create_time_diff'] = $v['status'] == 2 ? formatSecond($v['over_time'] - $v['create_time']) : formatSecond(time() - $v['create_time']);
                    $list[$k]['status'] = $v['status'] == 99 ? '已废弃' : '未作废';
                    $list[$k]['osList'] = $osList = $this->_deal_order_size_list($v['order_size_list']);
                    $list[$k]['osStat'] = ['order_count' => array_sum(array_column($osList, 'order_count')), 'shicai_count' => array_sum(array_column($osList, 'shicai_count')), 'jiaohuo_count' => array_sum(array_column($osList, 'jiaohuo_count')), 'jiaohuo_tail_count' => array_sum(array_column($osList, 'jiaohuo_tail_count')), 'delivery_count' => array_sum(array_column($osList, 'delivery_count')), 'daohuo_count' => array_sum(array_column($osList, 'daohuo_count'))];
                    $list[$k]['daohuo_count'] = $list[$k]['osStat']['daohuo_count'];
                    $list[$k]['jiaohuo_count'] = $list[$k]['osStat']['jiaohuo_count'];
                    $list[$k]['shicai_count'] = $list[$k]['osStat']['shicai_count'];
                    $list[$k]['factory_name'] = trim($list[$k]['factory_name']);
                    $list[$k]['group_name'] = trim($list[$k]['group_name']);
                    $list[$k]['caigou_over_time'] = intval($v['caigou_over_time']) > 0 ? date('Y-m-d H:i:s', intval($v['caigou_over_time'])) : '';
                    $list[$k]['caichuang_over_time'] = intval($v['caichuang_over_time']) > 0 ? date('Y-m-d H:i:s', intval($v['caichuang_over_time'])) : '';
                    $list[$k]['chejian_over_time'] = intval($v['chejian_over_time']) > 0 ? date('Y-m-d H:i:s', intval($v['chejian_over_time'])) : '';
                    $list[$k]['tail_over_time'] = intval($v['tail_over_time']) > 0 ? date('Y-m-d H:i:s', intval($v['tail_over_time'])) : '';
                    $list[$k]['shipment_time'] = intval($v['shipment_time']) > 0 ? date('Y-m-d H:i:s', intval($v['shipment_time'])) : '';
                    $list[$k]['over_time'] = intval($v['over_time']) > 0 ? date('Y-m-d H:i:s', intval($v['over_time'])) : '';
                    $list[$k]['is_auto_import'] = arrayGet($orderFromMap, $v['is_auto_import'], '');
                    $list[$k]['is_public'] = $v['is_public'] == 1 ? '是' : '否';

                    $list[$k]['off_pressing_level'] = arrayGet($processLevelMap, $v['off_pressing_level']);
                    $list[$k]['special_process_a_level'] = arrayGet($processLevelMap, $v['special_process_a_level']);
                    $list[$k]['special_process_b_level'] = arrayGet($processLevelMap, $v['special_process_b_level']);
                    $list[$k]['zj_level'] = arrayGet($processLevelMap, $v['zj_level']);
                    $list[$k]['is_new'] = $v['is_new'] ? '是' : '否';
                    $list[$k]['caichuang_position'] = arrayGet($caichuangPositionMap, $v['caichuang_position']);

                    $list[$k]['remark'] = trim($v['remark']);
                    $list[$k]['factory_outgo_name'] = trim($v['factory_outgo_name']);
                    $order_id_array[] = $v['id'];
                }
                break;
            default:
                $orderFromMap = config('mimo.order_from');
                foreach ($list as $k => $v) {
                    $list[$k]['shipment_time_diff'] = $v['status'] == 2 ? formatSecond($v['shipment_time'] - $v['over_time']) : formatSecond($v['shipment_time'] - time());
                    $list[$k]['create_time_diff'] = $v['status'] == 2 ? formatSecond($v['over_time'] - $v['shipment_time']) : formatSecond(time() - $v['shipment_time']);
                    $list[$k]['delete_text'] = $v['status'] == 99 ? '已废除' : '';
                    $list[$k]['osList'] = $osList = $this->_deal_order_size_list($v['order_size_list']);
                    $list[$k]['osStat'] = ['order_count' => array_sum(array_column($osList, 'order_count')), 'shicai_count' => array_sum(array_column($osList, 'shicai_count')), 'jiaohuo_count' => array_sum(array_column($osList, 'jiaohuo_count')), 'jiaohuo_tail_count' => array_sum(array_column($osList, 'jiaohuo_tail_count')), 'delivery_count' => array_sum(array_column($osList, 'delivery_count')), 'daohuo_count' => array_sum(array_column($osList, 'daohuo_count'))];
                    $list[$k]['ext_id'] = trim($list[$k]['ext_id']);
                    $list[$k]['factory_name'] = trim($list[$k]['factory_name']);
                    $list[$k]['group_name'] = trim($list[$k]['group_name']);
                    $list[$k]['is_auto_import'] = arrayGet($orderFromMap, $v['is_auto_import'], '');
                    $order_id_array[] = $v['id'];
                }
                break;
        }
    }

    private function _allList_order_material(&$list, $list_order_material, $order_id_array, $export)
    {
        switch ($export) {
            case true:
                $materialTypeMap = config('mimo.material_type');
                $list_stock_log = db('stock_log')
                    ->field('id,type,order_id,material_id,operate_num,remark,create_time')
                    ->where([
                        ['order_id', 'in', $order_id_array],
                        ['type', 'in', [0, 1]],
//                        ['remark', '=', '*使用库存'],
                    ])->order('id desc')->select();
                $list_material_stock = db('material_stock')
                    ->field('id,order_id,material_id,create_time')
                    ->where([
                        ['order_id', 'in', $order_id_array],
                    ])->order('id desc')->select();
                foreach ($list as $k => $v) {
                    $list[$k]['omList'] = [];
                    foreach ($list_order_material as $k2 => $sv) {
                        if ($v['id'] == $sv['order_id']) {
                            $sv['jing_material_dosage'] = round($v['quantity'] * $sv['material_dosage'], 2);
                            $sv['type'] = $materialTypeMap[$sv['type']];
                            $sv['caigou_user_name'] = trim($v['caigou_user_name']);
//                            $sv['caigou_over_time'] = intval($sv['caigou_over_time']) > 0 ? date('Y-m-d H:i:s', intval($sv['caigou_over_time'])) : '';
                            $sv['caigou_start_time'] = intval($sv['caigou_start_time']) > 0 ? date('Y-m-d H:i:s', intval($sv['caigou_start_time'])) : '';
                            $sv['tiaoshu_status_time_10'] = $sv['tiaoshu_status'] == 10 && intval($sv['tiaoshu_status_time']) > 0 ? date('Y-m-d H:i:s', intval($sv['tiaoshu_status_time'])) : '';
                            $sv['caigou_finish_time'] = intval($sv['caigou_finish_time']) > 0 ? date('Y-m-d H:i:s', intval($sv['caigou_finish_time'])) : '';
                            $sv['arrive_time'] = intval($sv['arrive_time']) > 0 ? date('Y-m-d H:i:s', intval($sv['arrive_time'])) : '';
                            $sv['caigou_confirm_time'] = intval($sv['caigou_confirm_time']) > 0 ? date('Y-m-d H:i:s', intval($sv['caigou_confirm_time'])) : '';
                            $sv['caigou_over_time'] = $sv['caigou_status'] == 1 && intval($sv['caigou_over_time']) > 0 ? date('Y-m-d H:i:s', intval($sv['caigou_over_time'])) : '';
                            $sv['caigou_over_time_2'] = $sv['caigou_status'] == 2 && intval($sv['caigou_over_time']) > 0 ? date('Y-m-d H:i:s', intval($sv['caigou_over_time'])) : '';
                            $sv['send_goods_time'] = $sv['send_goods_time'] ? date('Y-m-d H:i:s', intval($sv['send_goods_time'])) : '';
                            $sv['st_operate_num'] = '';//材料使用明细
                            $sv['st_remark'] = '';//材料使用操作
                            $sv['stock_in_time'] = '';//物料入库时间
                            $sv['stock_out_time'] = '';//物料出库时间
                            if ($list_stock_log != []) {//辅料库信息
                                foreach ($list_stock_log as $k3 => $v3) {
                                    if ($v3['order_id'] == $sv['order_id'] && $v3['material_id'] == $sv['material_id']
                                        && $v3['remark'] == '*使用库存') {
                                        $sv['st_operate_num'] = $v3['operate_num'];
                                        $sv['st_remark'] = $v3['remark'];
                                        break;
                                    }
                                }
                                foreach ($list_stock_log as $k3 => $v3) {
                                    if ($v3['order_id'] == $sv['order_id'] && $v3['material_id'] == $sv['material_id']
                                        && $v3['type'] == 1) {
                                        $sv['stock_in_time'] = intval($v3['create_time']) > 0 ? date('Y-m-d H:i:s', intval($v3['create_time'])) : '';
                                        break;
                                    }
                                }
                                foreach ($list_stock_log as $k3 => $v3) {
                                    if ($v3['order_id'] == $sv['order_id'] && $v3['material_id'] == $sv['material_id']
                                        && $v3['type'] == 0) {
                                        $sv['stock_out_time'] = intval($v3['create_time']) > 0 ? date('Y-m-d H:i:s', intval($v3['create_time'])) : '';
                                        break;
                                    }
                                }
                            }
                            if ($list_material_stock != []) {//面料库信息
                                foreach ($list_material_stock as $k3 => $v3) {
                                    if ($v3['order_id'] == $sv['order_id'] && $v3['material_id'] == $sv['material_id']) {
                                        $sv['stock_in_time'] = intval($v3['create_time']) > 0 ? date('Y-m-d H:i:s', intval($v3['create_time'])) : '';
                                        break;
                                    }
                                }
                            }
                            $list[$k]['omList'][] = $sv;
                        }
                    }
                }
                break;
            default:
                foreach ($list as $k => $v) {
                    $list[$k]['omList'] = [];
                    $list[$k]['approval_color_all'] = 1;// 是否全部批色
                    foreach ($list_order_material as $k2 => $sv) {
                        if ($v['id'] == $sv['order_id']) {
                            $sv['jing_material_dosage'] = round($v['quantity'] * $sv['material_dosage'], 2);
                            $sv['total_material_dosage'] = round(($v['quantity'] * $sv['material_dosage']) + ($v['quantity'] * $sv['material_dosage']) * $sv['loss'] / 100, 2);
                            // 余料使用
                            $sv['stock_use_num'] = $sv['operate_num_0'] - $sv['operate_num_2'];
                            // 物料状态
                            $sv['material_status'] = $this->getMaterialStatusV2($sv);
                            $sv['sku'] = $v['sku'];
                            $list[$k]['omList'][] = $sv;
                            $sv['type'] <> 'accessories' && $sv['caigou_status'] != 1 && $list[$k]['approval_color_all'] = 0;
                        }
                    }
                }
                break;
        }
    }

    private function _where_index($whereData)
    {
        $sql_leftjoin_order_material = "";
        $whereHaving = '1=1';
        $where_material_property = [];// 物料附加条件
        $whereRaw = '1=1 ';
        $where = [
            ["o.status", 'in', [0, 1, 2]],
//            ["o.status", 'in', [0, 1]],
//            ['o.client_status', '<>', 99],
            ['om.caigou_show', '>', 0]
        ];
        $clientOrdernum = $whereData['client_ordernum'] ?? '';
        $sku = $whereData['sku'] ?? '';
        $factorId = $whereData['factory_id'] ?? '';
        $orderStatus = $whereData['order_status'] ?? '';
        $createDateRange = $whereData['create_date_range'] ?? '';
        $isAutoImport = $whereData['is_auto_import'] ?? 0;
        $type = $whereData['type'] ?? '';
        switch (env('env_site')) {
            case 'riwei':
                $ext_id = $whereData['ext_id'] ?? '';
                $ext_id != '' && $where[] = ['o.ext_id', '=', $ext_id];
                break;
        }
        if ($clientOrdernum != '') {
            $where[0] = ["1", '=', 1];//清["o.status", 'in', [0, 1]],这个条件
            $where[1] = ["1", '=', 1];
            $where[] = ['o.client_ordernum', '=', $clientOrdernum];
        }
        if ($sku != '') {
            $where[0] = ["1", '=', 1];
            $where[1] = ["1", '=', 1];
            $where[] = ['o.sku', 'like', "%" . $sku . "%"];
        }
        if ($factorId) {
            $where[] = ['o.factory_id', '=', $factorId];
        }
        if ($createDateRange != '') {
            list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
            $where[] = ['o.create_time', 'between', [$startTime, $endTime + 86399]];
        }
        if ($isAutoImport > 0) {
            $where[] = ['o.is_auto_import', '=', $isAutoImport];
        }
        if ($type != '') {
            $where[] = ['o.type', '=', $type];
        }
        if ($orderStatus == 99) $where[] = ['o.status', '=', 99];
        elseif ($orderStatus == 999) $where[] = ['o.client_status', '=', 99];
        if ($orderStatus != '') {
            switch ($orderStatus) {
                case 1:
                    $where[] = ['o.caigou_status', '=', 0];
                    break;
                case 2:
                    $where[] = ['o.caigou_status', '=', 1];
                    $where[] = ['o.caichuang_status', '=', 0];
                    break;
                case 3:
                    $where[] = ['o.caichuang_status', '=', 1];
                    $where[] = ['o.chejian_status', '=', 0];
                    break;
                case 4:
                    $where[] = ['o.chejian_status', '=', 1];
                    $where[] = ['o.tail_status', '=', 0];
                    break;
                case 5:
                    $where[] = ['o.tail_status', '=', 1];
                    $where[] = ['o.real_shipment_status', '=', 0];
                    break;
                case 6:
                    $where[] = ['o.real_shipment_status', '=', 1];
                    $where[] = ['o.status', '=', 1];
                    break;
                case 7:
                    $where[] = ['o.status', '=', 2];
                    break;
            }
        }
        return [
            $where,
            $whereRaw,
            $whereHaving,
            $sql_leftjoin_order_material,
            $where_material_property,
        ];
    }

    private function _deal_order_size_list($order_size_list)
    {
        if (trim($order_size_list) == '') {
            return [];
        }
        $res = [];
        $list = explode(';', $order_size_list);
        foreach ($list as $k => $v) {
            $temp = explode(',', $v);
            $res[] = [
                'size_name' => $temp[1],
                'order_count' => $temp[2],
                'shicai_count' => $temp[3],
                'jiaohuo_count' => $temp[4],
                'jiaohuo_tail_count' => $temp[5],
                'delivery_count' => $temp[6],
                'daohuo_count' => $temp[7],
            ];
        }
        return $res;
    }

    private function getMaterialStatusV2($omInfo)
    {
        $result = [
            'is_make_tag' => $omInfo['is_make_tag'],//是否打标
            'is_caigou_start' => $omInfo['is_caigou_start'],    // 采购状态（0未开始，1采购中，2采购完成）
            'is_checkcloth' => $omInfo['need_checkcloth'],    // 验布状态（0无需验布，1验布未完成，2验布完成）
            'is_shrink' => $omInfo['need_shrink'],    // 缩水状态（0无需缩水，1缩水未完成，2缩水完成）
            'material_return' => 0, // 换料状态（0无换料，1换料中，2换料完成）
            'caigou_arrive_status' => $omInfo['is_caigou_start'],    // 采购状态与到料操作 合成（0未开始，1采购中，2采购完成 10已到料 20不显示内容）
        ];
        // 检测是否验布完成
        if ($omInfo['is_make_tag'] == 1 && $omInfo['need_checkcloth'] == 1 && $omInfo['cloth_0'] == $omInfo['tiaoshu']) {
            $result['is_checkcloth'] = 2;
        }
        // 检测是否缩水完成
        if ($omInfo['is_make_tag'] == 1 && $omInfo['need_shrink'] == 1 && $omInfo['cloth_1'] == $omInfo['tiaoshu']) {
            $result['is_shrink'] = 2;
        }
        // 换料状态
//        if ($omInfo['material_return_0'] > 0) {
//            $result['material_return'] = 1;
//        } elseif ($omInfo['material_return_1'] > 0) {
//            $result['material_return'] = 2;
//        } elseif ($omInfo['material_return_2'] > 0) {
//            $result['material_return'] = 1;
//        }
        //采购状态与到料操作 合成
        if ($omInfo['arrive_time_first'] > 0 && $result['caigou_arrive_status'] <= 1) {
            $result['caigou_arrive_status'] = 10;
        }
        if ($omInfo['tiaoshu_status'] == 10) {
            $result['caigou_arrive_status'] = 20;
        }
        return $result;
    }

    /**
     * 1,查询要查询的数据，并锁定，防止其它进程又再查询
     * 2，记录页数，并可知由此的文件是否写入完成
     * @author zhuguosen 905502314@qq.com
     * @date 2022/6/5
     */
    public function set_excel_data()
    {
        //1,查询要查询的数据，并锁定，防止其它进程又再查询
        $info = db('user_defined')->where(['lock' => 0, 'status' => 0,])->order('id asc')->limit(1)->find();
        if (!isset($info['id'])) {
            return ['code' => 10, 'msg' => '暂没数据'];
        }
        db('user_defined')->where(['id' => $info['id']])->update([
            'start_date' => date('Y-m-d H:i:s'),
            'lock' => 1,
        ]);
        list($filename, $uploadPath, $where) = $this->_set_excel_data_where($info);
        $count = $this->allList('count', 1, 1, $where);
        $limit = 1000;
        $page_max = floor(($count / $limit)) == ($count / $limit) ? ($count / $limit) : floor(($count / $limit)) + 1;
        for ($page = 1; $page <= $page_max; $page++) {
            $info = db('user_defined')->where(['id' => $info['id']])->find();
            if (!isset($info['id'])) {//如删除记录就停止进程
                break;
            }
            $data = $this->allList('list', $page, $limit, $where, true);
            $this->set_excel_file($filename, $data['data']);
            db('user_defined')->where(['id' => $info['id']])->update([
                'status_ext' => json_encode([
                    'count' => $count,
                    'page' => $page,
                    'limit' => $limit,
                ]),
                'file_url' => $filename,
                'upload_path' => $uploadPath,
            ]);
        }
        db('user_defined')->where(['id' => $info['id']])->update([
            'status' => 1,
            'file_url' => $filename,
            'upload_path' => $uploadPath,
            'end_date' => date('Y-m-d H:i:s'),
        ]);
        return ['code' => 0, 'msg' => '成功生成文件', 'data' => $filename];
    }

    private function _set_excel_data_where($info)
    {
        $uploadPath = 'upload/excel/' . date('Y-m-d') . "-{$info['id']}" . '.csv';
        $filename = env('root_path') . 'public/' . $uploadPath;
        $where = [];
        $label = [];
        $where = json_decode($info['where'], true);
        $label = json_decode($info['label'], true);
        $this->get_label_real($label);
//        $where['client_ordernum'] = '9074411';
        return [$filename, $uploadPath, $where];
    }

    /**
     * 得出适合的键值对--中文--字段名
     * @param $label
     * @author zhuguosen 905502314@qq.com
     * @date 2022/6/6
     */
    public function get_label_real($label)
    {
        $this->label_real = ['order' => [], 'material' => [],];
        if ($label['order'] != []) {
            foreach ($label['order'] as $k => $v) {
                foreach ($this->order_kv as $k2 => $v2) {
                    if ($k == $k2) {
                        $this->label_real['order'][] = [
                            'en' => $k2,
                            'cn' => $v2,
                        ];
                        break;
                    }
                }
            }
        }
        if ($label['material'] != []) {
            foreach ($label['material'] as $k => $v) {
                foreach ($this->material_kv as $k2 => $v2) {
                    if ($k == $k2) {
                        $this->label_real['material'][] = [
                            'en' => $k2,
                            'cn' => $v2,
                        ];
                        break;
                    }
                }
            }
        }
    }

    public function set_excel_file($filename, $list)
    {
        $list = $this->_set_excel_file_list($list);
        $data = $this->csv_export_f($list);
        @file_put_contents($filename, $data, FILE_APPEND);
    }

    private function _set_excel_file_list($list)
    {
        $res_list = [];
        if ($this->head_flag == 0) {
            $res_list[] = $this->head_txt();
            $this->head_flag = 1;
        }
        foreach ($list as $k => $v) {
            $temp_line = [];
            foreach ($this->label_real['order'] as $k2 => $v2) {
                $temp_line[] = $v[$v2['en']] ?? '';
            }
            if ($this->label_real['material'] != []) {
                foreach ($v['omList'] as $k2 => $v2) {
                    $temp_order_marterial = $temp_line;
                    foreach ($this->label_real['material'] as $k3 => $v3) {
                        $temp_order_marterial[] = $v2[$v3['en']] ?? '';
                    }
                    $res_list[] = $temp_order_marterial;
                }
            } else {
                $res_list[] = $temp_line;
            }
        }
        return $res_list;
    }

    public function head_txt()
    {
        $res = [];
        if ($this->label_real['order'] != []) {
            foreach ($this->label_real['order'] as $k => $v) {
                $res[] = $v['cn'];
            }
        }
        if ($this->label_real['material'] != []) {
            foreach ($this->label_real['material'] as $k => $v) {
                $res[] = $v['cn'];
            }
        }
        return $res;
    }

    /**
     * 生成csv内容
     */
    public function csv_export_f($expData)
    {
        // export file
        $csv = '';
//        foreach ($keys as $key) {
//            $csv .= '"' . iconv("UTF-8", "gb2312", $key) . '",';
//        }
//        $csv .= "\n";
        foreach ($expData as $expArr) {
            foreach ($expArr as $e_key => $exp) {
                if (!is_array($expArr[$e_key])) {
                    $csv .= iconv("UTF-8", "gbk", $this->escapeCSV($expArr[$e_key])) . ',';
                }
            }
            $csv .= "\n";
        }
        ob_end_clean();
        return $csv;
    }

    public function escapeCSV($str)
    {
        $str = str_replace(array(',', '"', "\n\r"), array('', '""', ''), $str);
        if ($str == "") {
            $str = '""';
        }
        return $str;
    }

    public function field_edit($label)
    {
        $order_head = ['下单时间', '客户订单号', '订单类型', '订单时效', '作废状态', 'SKU', '出货数', '车间数', '裁床数', '订单数量', '加工厂', '采购进度', '裁床进度', '车间进度', '尾部进度', '产品分组', '备注', '外发工厂',
            '加工费', '售价', '货期', '来源账号',
            '是否公共款', '款式', '品类'
            , '面料SKU', '面料种类', '面料供应商', '大烫', '二次工艺A', '二次工艺A程度', '二次工艺B', '二次工艺B程度', '二次工艺C', '二次工艺C程度', '是否新款', '裁剪方式'
        ];
        $material_head = ['客户订单号', 'SKU', '图片', '总数', '采购执行人', '材料名称', '材料SKU', '供应商', '型号', '单件用量', '批色时间', '采购量', '采购单位', '单价', '实际采购量', '条数'];

    }
}